/*
 * @lc app=leetcode.cn id=1161 lang=typescript
 *
 * [1161] 最大层内元素和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function maxLevelSum(root: TreeNode | null): number {
  const queue: TreeNode[] = [root];
  // 最大元素和
  let maxSum = root.val;
  // 最大元素和的层数
  let maxLevel = 1;
  let ans = 1;
  while (queue.length) {
    const size = queue.length;
    let sum = 0;
    // 计算当前层的元素和
    for (let i = 0; i < size; i++) {
      const node = queue.shift();
      sum += node.val;
      if (node.left) {
        queue.push(node.left);
      }
      if (node.right) {
        queue.push(node.right);
      }
    }
    // 当前层的元素和超过最大元素和，更新最大元素和和最大元素和的层数
    if (sum > maxSum) {
      maxSum = sum;
      ans = maxLevel;
    }
    // 增加层数
    maxLevel++;
  }
  return ans;
}
// @lc code=end
